package org.devocean.groupbuying.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.devocean.groupbuying.domain.Customer;
import org.devocean.groupbuying.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Component
public class EmailValidator implements Validator {

	@Autowired
	private CustomerService customerService;

	public boolean supports(Class<?> classe) {

		return Customer.class.isAssignableFrom(classe);
	}

	public void validate(Object target, Errors errors) {

		final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

		
		Customer customer = (Customer) target;
		if (!customerService.verifyCustomer(customer)) {
			errors.rejectValue("email", "exist.userName","email dosen't exist");
			
		}

		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(customer.getEmail());
		if (!matcher.matches()) {
			errors.rejectValue("email", "notmatch.email","email not match");
		}

	}

}
